package com.arvin.skin.core;

import android.app.Activity;
import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.text.TextUtils;

import com.arvin.skin.core.utils.ClassUtil;
import com.arvin.skin.core.utils.SkinPreference;
import com.arvin.skin.core.utils.SkinResources;
import com.arvin.skin.core.utils.SkinThemeUtils;

import java.lang.reflect.Method;
import java.util.Observable;

public class SkinManager extends Observable {
    private Application application;
    private SkinActivityLifecycle skinActivityLifecycle;
    private SkinManager(Application application) {
        this.application = application;
        SkinPreference.init(application);
        skinActivityLifecycle = new SkinActivityLifecycle();
        application.registerActivityLifecycleCallbacks(skinActivityLifecycle);
        SkinResources.init(application);

        loadSkin(SkinPreference.getInstance().getSkin());
    }

    private static SkinManager instance;
    public static void init(Application application){
        if (instance == null) {
            synchronized (SkinManager.class){
                if (instance == null) {
                    instance = new SkinManager(application);
                }
            }
        }
    }

    public static SkinManager getInstance() {
        return instance;
    }

    public void loadSkin(String path) {
        if (TextUtils.isEmpty(path)){
            SkinPreference.getInstance().setSkin("");
            SkinResources.getInstance().reset();
        }else {
            try {
                AssetManager assetManager = AssetManager.class.newInstance();
                Method addAssetPath = ClassUtil.getMethod(assetManager.getClass(),"addAssetPath",String.class);
                addAssetPath.setAccessible(true);
                addAssetPath.invoke(assetManager,path);
                Resources appResources = application.getResources();
                Resources skinResouces = new Resources(assetManager,appResources.getDisplayMetrics(),
                        appResources.getConfiguration());
                PackageManager packageManager = application.getPackageManager();
                PackageInfo info = packageManager.getPackageArchiveInfo(path,PackageManager.GET_ACTIVITIES);
                SkinResources.getInstance().applySkin(skinResouces,info.packageName);
                SkinPreference.getInstance().setSkin(path);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        setChanged();
        notifyObservers();
    }

    public void updateSkin(Activity activity){
        skinActivityLifecycle.updateSkin(activity);
    }
}
